<?php
namespace Controller;

use Slim\Http\Request;
use Slim\Http\Response;
use Slim\Container;


class ShareApi extends Base
{

    public function __construct(Container $container)
    {
        parent::__construct($container);

    }

    public function saveshare(Request $req, Response $res)
    {
        $validate = $this->guard->validateToken($req->getParam('tk_name'), $req->getParam('tk_value'));
        if ($validate === true) {
            $id = $req->getParam('id');
            $uid = $req->getParam('uid');
            $state = (int)$req->getParam('state');
            $integral = empty($req->getParam('integral'))?0:$req->getParam('integral');
            $rank = $this->remove_xss($req->getParam('rank'));
            if ($this->checkfrom->regex('number', $id) === false || $this->checkfrom->regex('number', $state) === false || $this->checkfrom->regex('number', $uid) === false || $this->checkfrom->regex('number', $integral) === false) {
                return $res->withStatus(400)->write('data error');
                exit;
            }
            $data = [
                'state' => $state,
                'integral' => $integral,
                'rank' => $rank,
                'updatetime' => time()
            ];
            if ($state === 3) {
                //审核成功
                $this->db->startTrans();
                $updateshare = $this->db->where(['id' => $id])->update('tcp_user_share', $data);
                $sqlstr = sprintf('UPDATE  `tcp_user` SET intergtal=intergtal+%s,updatetime=%s where uid = %s ',$integral, time(), $uid);
                $updateuser = $this->db->doSql($sqlstr);
                if($updateshare&&$updateuser){
                    $this->db->commit();
                    return $res->withStatus(200)->write('操作成功');
                    exit;
                }else{
                    $this->db->rollback();
                    return $res->withStatus(400)->write('操作失败');
                    exit;
                }


            } else {
                $updateshare = $this->db->where(['id' => $id])->update('tcp_user_share', $data);
                if($updateshare){
                    $this->db->commit();
                    return $res->withStatus(200)->write('操作成功');
                    exit;
                }else{
                    $this->db->rollback();
                    return $res->withStatus(400)->write('操作失败');
                    exit;
                }

            }


        } else {
            return $res->withStatus(400)->write('guard error');
            exit;
        }

    }


}